package com.loongtech.bi.action.newsystem;

import com.loongtech.bi.action.authManagement.ResultData;
import com.loongtech.bi.entity.POJO.Page;
import com.loongtech.bi.entity.system.EntityAdvConfig;
import com.loongtech.bi.entity.system.EntitySysProject;
import com.loongtech.bi.manager.system.AdvConfigManager;
import com.loongtech.bi.manager.system.SyncInfoLogManager;
import com.loongtech.bi.manager.system.SysProjectManager;
import com.loongtech.bi.support.ExcelUtils;
import com.loongtech.core.util.RetCode;
import com.loongtech.core.util.Utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * ClassName: AdvConfigAction
 *
 * @author liuchen
 * @Description: 广告配置
 * @date 2016-11-14 下午5:04:18
 */
@RestController
@Scope("prototype")
@RequestMapping("/advsysconfig")
public class AdvSysConfigAction {
    @Resource
    private AdvConfigManager advConfigManager;
    @Resource(name = "systemConfig")
    private SystemConfig systemConfig;
    @Resource
    private SysProjectManager sysProjectManager;
    @Resource
    private SyncInfoLogManager syncInfoLogManager;

    /**
     * 查询
     */
    @RequestMapping(value = "list.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<?> searchByCriteria(@RequestParam Integer curPage, @RequestParam Integer pageSize, EntityAdvConfig entityConfig) {
        Page<List<EntityAdvConfig>> list;
        try {
            list = advConfigManager.queryByCriteria(curPage, pageSize, entityConfig);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultData.otherException();
        }
        return new ResultData<>(RetCode.eSuccess.getErrorcode(), list);
    }


    @RequestMapping(value = "add.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> add(EntityAdvConfig entity) {
        if (Utils.isEmptyStr(entity.getId())) {
            entity.setId(RandomStringUtils.randomAlphanumeric(6));
        }
        if ("mid".equals(systemConfig.getServerType())) {
            if (entity.getGameId() == null) {
                return new ResultData<>(RetCode.eEmptyGameId.getErrorcode(), RetCode.eEmptyGameId.getErrorMsg());
            }
            Map<String, Object> params = new HashMap<>();
            try {
                EntitySysProject project = sysProjectManager.getByQuery("from EntitySysProject where id = ?", entity.getGameId());
                params.put("id", entity.getId());
                params.put("affiliation", entity.getAffiliation());
                params.put("actName", entity.getActName());
                params.put("channelName", entity.getChannelName());
                params.put("agent", entity.getAgent());
                params.put("platform", entity.getPlatform());
                params.put("paytype", entity.getPaytype());
                params.put("advPosition", entity.getAdvPosition());
                String url = project.getProjectUrl() + "/advsysconfig/add.do";
                System.out.println("广告配置请求地址为:" + url);
                String res = Utils.httpPost(url, params);
                if (res.contains("操作成功")) {
                    advConfigManager.persist(entity);
                    return ResultData.success();
                }
                return ResultData.otherException();
            } catch (Exception e) {
                e.printStackTrace();
                return ResultData.otherException();
            }
        } else {
            try {
                List<EntityAdvConfig> list = advConfigManager.findAll();
                ResultData<String> res = validate(entity, true, list);
                if (res != null) {
                    return res;
                }
                advConfigManager.persist(entity);
                advConfigManager.init();
                return ResultData.success();
            } catch (Exception ex) {
                ex.printStackTrace();
                return ResultData.otherException();
            }
        }
    }

    @RequestMapping(value = "modify.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> modify(EntityAdvConfig entity) {
        if ("mid".equals(systemConfig.getServerType())) {
            if (entity.getGameId() == null) {
                return new ResultData<>(RetCode.eEmptyGameId.getErrorcode(), RetCode.eEmptyGameId.getErrorMsg());
            }
            Map<String, Object> params = new HashMap<>();
            try {
                EntitySysProject project = sysProjectManager.getByQuery("from EntitySysProject where id = ?", entity.getGameId());
                params.put("id", entity.getId());
                params.put("affiliation", entity.getAffiliation());
                params.put("actName", entity.getActName());
                params.put("channelName", entity.getChannelName());
                params.put("agent", entity.getAgent());
                params.put("platform", entity.getPlatform());
                params.put("paytype", entity.getPaytype());
                params.put("advPosition", entity.getAdvPosition());
                String url = project.getProjectUrl() + "/advsysconfig/modify.do";
                System.out.println("广告配置请求地址为:" + url);
                String res = Utils.httpPost(url, params);
                if (res.contains("操作成功")) {
                    advConfigManager.merge(entity);
                    return ResultData.success();
                }
                return ResultData.otherException();
            } catch (Exception e) {
                e.printStackTrace();
                return ResultData.otherException();
            }
        } else {
            try {
                List<EntityAdvConfig> list = advConfigManager.findAll();
                ResultData<String> res = validate(entity, false, list);
                if (res != null) {
                    return res;
                }
                EntityAdvConfig cur = advConfigManager.get(entity.getId());
                if (cur != null) {
                    advConfigManager.merge(entity);
                    advConfigManager.init();
                    return ResultData.success();
                } else {
                    return new ResultData<>(RetCode.eNotExistGourp.getErrorcode(), RetCode.eNotExistGourp.getErrorMsg());
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                return ResultData.otherException();
            }
        }
    }

    @RequestMapping(value = "delete.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ResultData<String> delete(String id) {
        if ("mid".equals(systemConfig.getServerType())) {
            EntityAdvConfig advEntity = advConfigManager.get(id);
            Map<String, Object> params = new HashMap<>();
            try {
                EntitySysProject project = sysProjectManager.getByQuery("from EntitySysProject where id = ?", advEntity.getGameId());
                params.put("id", advEntity.getId());
                String url = project.getProjectUrl() + "/advsysconfig/delete.do";
                System.out.println("广告配置请求地址为:" + url);
                String res = Utils.httpPost(url, params);
                if (res.contains("操作成功")) {
                    advConfigManager.removeById(id);
                    return ResultData.success();
                }
                return ResultData.otherException();
            } catch (Exception e) {
                e.printStackTrace();
                return ResultData.otherException();
            }
        } else {
            try {
                EntityAdvConfig cur = advConfigManager.get(id);
                if (cur != null) {
                    advConfigManager.removeById(id);
                    advConfigManager.init();
                    return ResultData.success();
                } else {
                    return new ResultData<>(RetCode.eNotExistGourp.getErrorcode(), RetCode.eNotExistGourp.getErrorMsg());
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                return ResultData.otherException();
            }
        }
    }

    @RequestMapping(value = "upload", method = {RequestMethod.POST})
    public ResultData<String> upload(@RequestParam(value = "file", required = false) CommonsMultipartFile file) throws IOException {
        if (file == null || file.getSize() <= 0 || file.getOriginalFilename() == null) {
            return new ResultData<>(RetCode.eEmptyUploadFile.getErrorcode(), RetCode.eEmptyUploadFile.getErrorMsg());
        }
        String fileName = file.getOriginalFilename();
        String id = UUID.randomUUID().toString();
        // 文件的相对路径
        String subPath = "AdvSysConfig_" + id + "_" + fileName;
        // 文件的绝对路径
        String filePath = systemConfig.getFileParentPath() + subPath;
        System.out.println("upload file path: " + filePath);
        File tmpdir = new File(systemConfig.getFileParentPath());
        if (!tmpdir.exists()) {
            tmpdir.mkdir();
        }
        File newfile = new File(filePath);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), newfile);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultData<>(RetCode.eIOUploadFile.getErrorcode(), RetCode.eIOUploadFile.getErrorMsg());
        }
        return parseExcel(newfile);
    }

    public ResultData<String> parseExcel(File file) {
        StringBuilder errorid = new StringBuilder();
        try {
            List<EntityAdvConfig> tmp = parseUploadedExcel(file);
            List<EntityAdvConfig> list = advConfigManager.findAll();
            StringBuilder InsertSQLPre = new StringBuilder("insert into bi_advconfig(id,affiliation,actName,channelName,agent,platform,paytype,advPosition) values ");
            if (tmp != null && tmp.size() > 0) {
                asd:
                for (EntityAdvConfig e : tmp) {
                    for (EntityAdvConfig adv : list) {
                        if (adv.getId().equals(e.getId())) {
                            errorid.append(e.getId()).append(",");
                            continue asd;
                        }
                    }
                    advConfigManager.persist(e);
                    InsertSQLPre.append("('").append(e.getId()).append("','").append(e.getAffiliation()).append("','").append(e.getActName())
                            .append("','").append(e.getChannelName()).append("','").append(e.getAgent()).append("','").append(e.getPlatform()).append("','").append(e.getPaytype()).append("','").append(e.getAdvPosition()).append("'),");
                    advConfigManager.init();
                }
                String isql = InsertSQLPre.substring(0, InsertSQLPre.length() - 1);
                syncInfoLogManager.add(tmp.get(0).getGameId().toString(), isql);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultData<>(RetCode.eParseExcel.getErrorcode(), RetCode.eParseExcel.getErrorMsg());
        } finally {
            if (file != null && file.exists()) {
                file.delete();
            }
        }
        if (errorid.length() > 0) {
            return new ResultData<>(RetCode.eSuccess.getErrorcode(), "解析成功！包含重复短链 ： " + errorid.substring(0, errorid.length() - 1));
        } else {
            return ResultData.success();
        }
    }

    private List<EntityAdvConfig> parseUploadedExcel(File file) throws Exception {
        List<EntityAdvConfig> result = new ArrayList<>();
        InputStream input = new FileInputStream(file);
        Workbook wb = WorkbookFactory.create(input);
        Sheet tempSheet = wb.getSheetAt(0);
        if (tempSheet == null) {
            IOUtils.closeQuietly(input);
            System.out.println("Error---------------------------excel内容为空,数据错误！");
            throw new Exception("excel内容为空,数据错误");
        }
        int rowNum = tempSheet.getLastRowNum();// 获得总行数
        for (int i = 0; i <= rowNum; i++) {
            Row row = tempSheet.getRow(i);
            if (row == null) {
                continue;
            }
            String gameId = ExcelUtils.getCellValue(row.getCell(0));
            String id = "".equals(ExcelUtils.getCellValue(row.getCell(1))) ? RandomStringUtils.randomAlphanumeric(6) : ExcelUtils.getCellValue(row.getCell(1));
            String affiliation = ExcelUtils.getCellValue(row.getCell(2));
            String actName = ExcelUtils.getCellValue(row.getCell(3));
            String channelName = ExcelUtils.getCellValue(row.getCell(4));
            String agent = ExcelUtils.getCellValue(row.getCell(5));
            String platform = ExcelUtils.getCellValue(row.getCell(6));
            String paytype = ExcelUtils.getCellValue(row.getCell(7));
            String advPosition = ExcelUtils.getCellValue(row.getCell(8));
            if ("".equals(gameId) || "".equals(affiliation) || "".equals(actName) || "".equals(channelName) || "".equals(agent) || "".equals(platform) || "".equals(paytype) || "".equals(advPosition)) {
                continue;
            }
            EntityAdvConfig e = new EntityAdvConfig();
            e.setGameId(Integer.parseInt(gameId));
            e.setId(id);
            e.setAffiliation(affiliation);
            e.setActName(actName);
            e.setChannelName(channelName);
            e.setAgent(agent);
            e.setPlatform(platform);
            e.setPaytype(paytype);
            e.setAdvPosition(advPosition);
            result.add(e);
        }
        IOUtils.closeQuietly(input);
        return result;
    }


    private ResultData<String> validate(EntityAdvConfig ebp, boolean isAdd, List<EntityAdvConfig> ebpList) {
        if (Utils.isEmptyStr(ebp.getAffiliation())) {
            return new ResultData<>(RetCode.eEmptyBelong.getErrorcode(), RetCode.eEmptyBelong.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getActName())) {
            return new ResultData<>(RetCode.eEmptyActiveName.getErrorcode(), RetCode.eEmptyActiveName.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getChannelName())) {
            return new ResultData<>(RetCode.eEmptyChanName.getErrorcode(), RetCode.eEmptyChanName.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getAgent())) {
            return new ResultData<>(RetCode.eEmptyAgent.getErrorcode(), RetCode.eEmptyAgent.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getPlatform()) || "0".equals(ebp.getPlatform())) {
            return new ResultData<>(RetCode.eEmptyChanPlat.getErrorcode(), RetCode.eEmptyChanPlat.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getPaytype())) {
            return new ResultData<>(RetCode.eEmptySettlement.getErrorcode(), RetCode.eEmptySettlement.getErrorMsg());
        }
        if (Utils.isEmptyStr(ebp.getAdvPosition())) {
            return new ResultData<>(RetCode.eEmptyAdvPlace.getErrorcode(), RetCode.eEmptyAdvPlace.getErrorMsg());
        }

        if (isAdd) {
            // 如果是添加，则ID不能重
            for (EntityAdvConfig e : ebpList) {
                if (ebp.getId().equals(e.getId())) {
                    return new ResultData<>(RetCode.eIdExist.getErrorcode(), RetCode.eIdExist.getErrorMsg());
                }
            }
        }
        return null;
    }
}
